const request = require('request');
const wechat = require('wechat');
const cache = require('memory-cache')
const sha1 = require('sha1')
const wechatAPI = require('wechat-api');

// 生产环境
// const appid = "wx0cf6e1b038363a06";
// const appSecret = "38a563637a7fcaf0e672bbfea26c8b47";

// 卡莫生产环境
const appid = "wxbc2631875fcdbfb3";
const appSecret = "ebf3cef71be97536af4c730c4c9ab82a";

// 开发环境
// const appid = "wx7495a9020ba761d7";
// const appSecret = "c18b55a9b627c9c5ba9de47a4f5aac98";



let config = {
    grant_type: 'client_credential',
    appid: appid,
    secret: appSecret,
    noncestr: 'Wm3WZYTPz0wzccnW',
    accessTokenUrl: 'https://api.weixin.qq.com/cgi-bin/token',
    ticketUrl: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
    cache_duration: 7200*1000
}

let wxConfig = {
    token: 'text',
    appid: appid,
    secret: appSecret,
    encodingAESKey: 'j5W4soVaYsZcthl9GVuI4vcdQvMXERHpDQOVEQeQ6ai',
    checkSignature: true // 可选，默认为true。由于微信公众平台接口调试工具在明文模式下不发送签名，所以如要使用该测试工具，请将其设置为false 
}


const wxInterface = {

    userAccessToken(code, callback) { // 获取access_token 获取用户信息的access_token与基本的accessToken不同
        let tokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.appid}&secret=${config.secret}&code=${code}&grant_type=authorization_code`;
        request(tokenUrl, (error, response, body) => {
            if (response && response.statusCode && response.statusCode === 200) {
                try {
                    body = JSON.parse(body);
                } catch (e) {
                    body = null;
                }
                callback && callback(body);
            }
        });
    },

    getWxUserInfo(code) {     //获取用户信息
        return new Promise((resolve, reject) => {
            wxInterface.userAccessToken(code, (data) => {
                if (data) {
                    if (data.errcode) {
                        reject(data)
                    } else {
                        console.log(data, 1000000)
                        var tokenUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${data.access_token}&openid=${data.openid}&lang=zh_CN`;
                        request(tokenUrl, function (error, response, body) {
                            if (response && response.statusCode && response.statusCode === 200) {
                                try {
                                    body = JSON.parse(body);
                                    body.access_token = data.access_token;
                                    body.refresh_token = data.refresh_token;
                                } catch (e) {
                                    body = null;
                                }
                                console.log(body, 8000000)
                                resolve(body);
                            }
                        });
                    }
                }
            });
        }).catch(error => {
            console.log(error)
        })
    },

    getAccessToken() { // 获取access_token 获取用户信息的access_token与基本的accessToken不同
        return new Promise((resolve, reject) => {
            let tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
            console.log(tokenUrl)
            request(tokenUrl, (error, response, body) => {
                console.log(body)
                if (response && response.statusCode && response.statusCode === 200) {
                    try {
                        body = JSON.parse(body);
                    } catch (e) {
                        body = null;
                    }
                    resolve(body)
                }
            });
        }).catch(error => {
            console.log(error)
        })
    },

    sign(url, accessToken, callback) {
        var noncestr = config.noncestr,
            timestamp = Math.floor(Date.now() / 1000), //精确到秒
            jsapi_ticket;
            ticket=cache.get('ticket')
            console.log('判断权限')
            console.log(cache.get('ticket'))
            
        if (ticket) {
            jsapi_ticket = ticket;
            console.log('本来就有权限')
            console.log('1' + 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url);
            callback({
                noncestr: noncestr,
                timestamp: timestamp,
                url: url,
                jsapi_ticket: jsapi_ticket,
                signature: sha1('jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url)
            });
        } else {
            console.log('重新刷新权限')
            request(config.ticketUrl + '?access_token=' + accessToken + '&type=jsapi', function (error, resp, json) {
                console.log('-----------')
                console.log('-----------')
                console.log('-----------')
                console.log(json)
                console.log('-----------')
                console.log('-----------')
                console.log('-----------')
                console.log(error)
                console.log('-----------')
                console.log('-----------')
                console.log('-----------')
                if (!error) {
                    var ticketMap = JSON.parse(json);
                    cache.put('ticket', ticketMap.ticket, config.cache_duration);  //加入缓存
                    console.log('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url);
                    callback({
                        appid,
                        noncestr: noncestr,
                        timestamp: timestamp,
                        url: url,
                        jsapi_ticket: ticketMap.ticket,
                        signature: sha1('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url)
                    });
                }
            })
        }
    },
    wechatApi: new wechatAPI(config.appid, config.secret),
    wxConfig: wxConfig,
    wechat: wechat
}

module.exports = wxInterface;



// sign(url, callback) {
//     var noncestr = config.noncestr,
//         timestamp = Math.floor(Date.now() / 1000), //精确到秒
//         jsapi_ticket;
//     if (cache.get('ticket')) {
//         jsapi_ticket = cache.get('ticket');
//         console.log('1' + 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url);
//         callback({
//             noncestr: noncestr,
//             timestamp: timestamp,
//             url: url,
//             jsapi_ticket: jsapi_ticket,
//             signature: sha1('jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url)
//         });

//     } else {
//         request(config.accessTokenUrl + '?grant_type=' + config.grant_type + '&appid=' + config.appid + '&secret=' + config.secret, function (error, response, body) {
//             if (!error && response.statusCode == 200) {
//                 var tokenMap = JSON.parse(body);
//                 request(config.ticketUrl + '?access_token=' + tokenMap.access_token + '&type=jsapi', function (error, resp, json) {
//                     if (!error && response.statusCode == 200) {
//                         var ticketMap = JSON.parse(json);
//                         cache.put('ticket', ticketMap.ticket, config.cache_duration);  //加入缓存
//                         console.log('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url);
//                         callback({
//                             appid,
//                             noncestr: noncestr,
//                             timestamp: timestamp,
//                             url: url,
//                             jsapi_ticket: ticketMap.ticket,
//                             signature: sha1('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url)
//                         });
//                     }
//                 })
//             }
//         })
//     }
// },
